#include "comboboxdelegate.h"

#include <QComboBox>
#include <QPainter>

ComboBoxDelegate::ComboBoxDelegate(const QStringList &optionNames, QObject *parent)
    : QStyledItemDelegate(parent)
    , m_optionNames(optionNames)
{}

QWidget *ComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QComboBox *combo = new QComboBox(parent);
    combo->addItems(m_optionNames);
    return combo;
}

void ComboBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    // QStyleOptionViewItem opt = option;
    // initStyleOption(&opt, index);
    // // 自定义绘制代码（例如显示当前选中项）
    // painter->drawText(opt.rect,  Qt::AlignCenter, index.data().toString());
    QStyledItemDelegate::paint(painter, option, index);
}

void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox *combo = qobject_cast<QComboBox *>(editor);
    int idx = index.model()->data(index, Qt::EditRole).toInt();
    if(combo && idx < m_optionNames.size()) {
        combo->setCurrentIndex(idx);
    }
}

void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox *combo = qobject_cast<QComboBox *>(editor);
    if(combo) {
        model->setData(index, combo->currentIndex(), Qt::EditRole);
    }
}

QSize ComboBoxDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    return QStyledItemDelegate::sizeHint(option, index);
}

void ComboBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyledItemDelegate::updateEditorGeometry(editor, option, index);
}
